<template>
  <el-card shadow="never">
    <el-form
      class="login-form"
      ref="form"
      :model="form"
      :rules="rules"
      label-width="150px"
    >
      <el-form-item label="广告位名称" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          class="login-btn"
          type="primary"
          :loading="loading"
          @click="onSubmit"
          >提交</el-button
        >
        <el-button
          v-if="!isEdit"
          class="login-btn"
          :loading="loading"
          @click="onReset"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
import { Form } from 'element-ui'
import Vue from 'vue'
import { getSpaceById, saveOrUpdate } from '@/services/advert-space.ts'
export default Vue.extend({
  name: 'AdvertSpaceForm',

  props: {
    editId: {
      type: String,
      default: ''
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },

  data () {
    return {
      form: {
        name: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入广告位名称', trigger: 'blur' }
        ]
      },
      loading: false
    }
  },

  created () {
    if (this.isEdit) {
      this.setSpace()
    }
  },

  methods: {
    async setSpace () {
      const { data } = await getSpaceById(parseInt(this.editId))
      this.form = data.content
    },
    onSubmit () {
      const form = this.$refs.form as Form
      form.validate((va) => {
        if (va) {
          this.$confirm('是否提交数据?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(async () => {
              this.loading = true
              await saveOrUpdate(this.form)

              this.$message.success('操作成功')
              this.$router.go(-1)
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消操作'
              })
            })
        }
      })
    },
    onReset () {
      const form = this.$refs.form as Form
      form.resetFields()
      this.form.name = ''
    }
  }
})
</script>

<style lang="scss" scoped>
</style>
